<?php

namespace app\controllers;

use app\behaviors\TestBehavior;
use app\models\Country;
use app\models\CountrySearch;
use Yii;
use yii\filters\AccessControl;
use yii\filters\Cors;
use yii\helpers\VarDumper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CountryController implements the CRUD actions for Country model.
 */
class CountryController extends Controller
{
    // 指定默认的动作id
    public $defaultAction = 'index';


    // 修改布局 文件 对应的文件是 /views/layouts/new.php
    // 设置成 false 不使用布局
    public $layout = 'new';

    /**
     * 过滤器
     * @inheritDoc
     */
    public function behaviors()
    {
        return array_merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'index' => ['get','POST'], // VerbFilter 检查请求动作的 HTTP 请求方式是否允许执行
                        'delete' => ['POST'],
                    ],
                ],
                'test' => [
                    'class' => TestBehavior::className(),
//                    'only' => ['index', 'view'],// 指定哪些动作使用缓存
//                    'except' => [], // 指定哪些动作不使用缓存
                ],
//                'access' => [
//                    'class' => AccessControl::className(),
//                    'only' => ['create', 'update'],
//                    'rules' => [
//                        // 允许认证用户
//                        [
//                            'allow' => true,
//                            'roles' => ['@'],
//                        ],
//                        // 默认禁止其他用户
//                    ],
//                ],
                // 跨域处理
                'cors' => [
                    'class' => Cors::className(),
                    'cors' => [
                        'Origin' => ['http://www.myserver.net'],
                        'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
                    ],
                    'actions' => [
                        // 为 login 动作 增加 Access-Control-Allow-Credentials 参
                        'login' => [
                            'Access-Control-Allow-Credentials' => true,
                        ]
                    ]
                ],
            ]
        );
    }

    /**
     * Desc: 测试对象事件
     * Auth: hello pan
     * Date: 9/14/25 8:39 PM
     * @param $event
     */
    public function testEventHandler($event)
    {
        var_dump('我是对象事件处理器'.$event->name);
    }

    public function actionEvents()
    {
        echo Yii::getAlias('@app');

        // 添加事件
        $this->on('test_event', function ($event) {
            VarDumper::dump($event->name);
        });

        // 增加 事件
        $this->on('test_event', [$this, 'testEventHandler']);


        // 触发事件
        $this->trigger('test_event');


    }

    /**
     * Desc: 操作行为执行前事件
     * Auth: hello pan
     * Date: 9/13/25 10:08 PM
     * @param $action
     * @return true
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        parent::beforeAction($action); // TODO: Change the autogenerated stub

        return true;
    }

    /**
     * Desc: 操作行为执行后事件
     * Auth: hello pan
     * Date: 9/13/25 10:09 PM
     * @param $action
     * @param $result
     * @return mixed
     */
    public function afterAction($action, $result)
    {
        $aa = parent::afterAction($action, $result); // TODO: Change the autogenerated stub

        // 处理执行后的处理

        return $aa;

    }


    public function actionForward()
    {
        // 重定向到其他地址
        return $this->redirect('/');

    }
    public function actionHelloWorld()
    {

        //获取请求参数
        p($this->request->queryParams);
        // 直接返回字符串

        return 'Hello world';

    }

    /**
     * Lists all Country models.
     *
     * @return string
     */
    public function actionIndex()
    {

        Yii::error('我是日志信息：22222');

        $session = Yii::$app->session;
        p($session->isActive);
        $session->set('name', ['aa' => 123]);
        $session['name'] = ['aa' => 444];
        $nam = $session->get('name');
//        $session->removeAll();
        p($nam);



        // cookie 的使用

        $cookies = Yii::$app->response->cookies;

        // 在要发送的响应中添加一个新的 cookie
        $cookies->add(new \yii\web\Cookie([
            'name' => 'language',
            'value' => 'zh-CN',
        ]));

        p($cookies->get('language'));

        // 删除一个 cookie
        //$cookies->remove('language');

        $searchModel = new CountrySearch();
        $dataProvider = $searchModel->search($this->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
        // 设置响应参数为json 数据
        $response = Yii::$app->response;
        $response->format = \yii\web\Response::FORMAT_JSON;
//        $response->data = [
//            'code' => 200,
//            'message' => 'success',
//            'data' => [
//                'name' => 'hello world',
//                'code' => '1222',
//            ],
//        ];
        return [
            'code' => 200,
            'message' => 'success',
            'data' => [
                'name' => 'hello world',
                'code' => '1222',
            ],
        ];

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Country model.
     * @param string $code 编号
     * @return string
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($code)
    {

        var_dump($this->request->getQueryParams());
        var_dump($this->request->getHeaders()->toArray());
        var_dump($this->request->url);
        var_dump($this->request->userIP);


        $model = $this->findModel($code);
        // 模型可以使用属性获取 也可以使用数组访问
        // $model->name;
        // $model['name'];

        // 通过属性获取属性值
        // p($model->getAttribute('name'));
        // 获取属性标签名  名称
        // p($model->getAttributeLabel('name'));die;

        // 第一种是使用 attributes 获取数组
        //$array = $model->attributes;

        // 使用model 的toArray() 方法  ,可以指定要返回的字段
        //$array = $model->toArray(['code','name'],['code_name']);
        $array = $model->toArray([],['code_name']);
//        p($array);die;

        // 不使用样式渲染视图
        // return $this->renderPartial('view',['model' => $model,]);

        // 使用ajax渲染视图
        //return $this->renderAjax('view',['model' => $model,]);
        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Country model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Country();

        // 设置场景
        // $model->scenario = Country::SCENARIO_CREATE;

        // 块赋值
        // $model->attributes = $this->request->post();

        if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['view', 'code' => $model->code]);
            }
        } else {
            $model->loadDefaultValues();
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Country model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $code 编号
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($code)
    {
        $model = $this->findModel($code);

        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
            return $this->redirect(['view', 'code' => $model->code]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Country model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $code 编号
     * @return \yii\web\Response
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($code)
    {
        $this->findModel($code)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Country model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $code 编号
     * @return Country the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($code)
    {
        if (($model = Country::findOne(['code' => $code])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
